const COS = require('cos-nodejs-sdk-v5');
const fs = require('fs');
const path = require('path');

// 腾讯云 COS 配置 - 参照 cosUploader.js 的配置
const COS_CONFIG = {
  SecretId: process.env.COS_SECRET_ID || 'AKIDvx7ERG4nOpV9h5LRM709KNJ9xtsjnwCK',
  SecretKey: process.env.COS_SECRET_KEY || '4z8A3oU2QirpdLuNgopgNtYbaVH6rW1S',
  Bucket: process.env.COS_BUCKET || 'baoqu-host-manager-1252921383',
  Region: process.env.COS_REGION || 'ap-guangzhou'
};

// 初始化COS客户端
const cos = new COS({
  SecretId: COS_CONFIG.SecretId,
  SecretKey: COS_CONFIG.SecretKey
});

// 列出可用的 exe 文件
async function listExeFiles() {
  try {
    console.log('🔍 正在获取腾讯云 COS 文件列表...');
    
    // 使用 COS SDK 获取文件列表
    const result = await cos.getBucket({
      Bucket: COS_CONFIG.Bucket,
      Region: COS_CONFIG.Region,
      Prefix: 'releases/'
    });
    
    if (result.Contents) {
      const exeFiles = result.Contents
        .filter(item => item.Key && item.Key.endsWith('.exe'))
        .map(item => path.basename(item.Key))
        .sort();
      
      console.log(`✅ 找到 ${exeFiles.length} 个 exe 文件:`, exeFiles);
      return exeFiles;
    }
    
    console.log('⚠️  没有找到 exe 文件，使用测试数据');
    return [
      'whistle-client-v1.0.0.exe',
      'whistle-client-v1.1.0.exe',
      'whistle-client-v1.2.0.exe',
      'whistle-client-v1.3.0.exe',
      'whistle-client-v2.0.0.exe'
    ];
  } catch (error) {
    console.error('Failed to list exe files:', error);
    console.log('⚠️  使用测试数据作为备选');
    // 返回测试数据作为备选
    return [
      'whistle-client-v1.0.0.exe',
      'whistle-client-v1.1.0.exe',
      'whistle-client-v1.2.0.exe',
      'whistle-client-v1.3.0.exe',
      'whistle-client-v2.0.0.exe'
    ];
  }
}

// 下载 exe 文件
async function downloadExeFile(fileName, downloadPath, progressCallback) {
  return new Promise((resolve, reject) => {
    try {
      const startTime = Date.now();
      const localPath = path.join(downloadPath, fileName);
      
      console.log(`开始下载: ${fileName}`);
      console.log(`保存到: ${localPath}`);
      
      // 使用 COS SDK 的 getObject 方法进行签名下载，支持进度回调
      const cloudPath = `releases/${fileName}`;
      
      // 使用COS SDK的onProgress回调来监控下载进度
      cos.getObject({
        Bucket: COS_CONFIG.Bucket,
        Region: COS_CONFIG.Region,
        Key: cloudPath,
        Output: localPath,
        onProgress: function(progressData) {
          // progressData包含: { loaded, total, speed, percent }
          const { loaded, total, speed, percent } = progressData;
          const progressPercent = percent * 100; // 转换为百分比
          
          if (progressCallback) {
            progressCallback(progressPercent, loaded, total, speed);
          }
          
          console.log(`下载进度: ${progressPercent.toFixed(1)}% (${(loaded / 1024 / 1024).toFixed(2)} MB / ${(total / 1024 / 1024).toFixed(2)} MB) 速度: ${(speed / 1024 / 1024).toFixed(1)} MB/s`);
        }
      }, (err, data) => {
        if (err) {
          console.error('COS 下载失败:', err);
          reject(new Error(`COS 下载失败: ${err.message}`));
          return;
        }
        
        try {
          // 获取文件信息
          const stats = fs.statSync(localPath);
          const downloadTime = Date.now() - startTime;
          
          console.log(`✅ 下载成功: ${localPath}`);
          console.log(`文件大小: ${(stats.size / 1024 / 1024).toFixed(2)} MB`);
          
          // 返回格式必须与 menu.js 中的使用完全匹配
          resolve({
            success: true,
            localPath,
            fileSize: stats.size,
            downloadTime
          });
        } catch (statError) {
          reject(new Error(`获取文件信息失败: ${statError.message}`));
        }
      });
      
    } catch (error) {
      reject(error);
    }
  });
}

// 导出模块 - 确保与 menu.js 中的 require('./cosDownloader') 匹配
module.exports = {
  listExeFiles,
  downloadExeFile
};
